/* global window */
import modelExtend from 'dva-model-extend'
import { config } from 'utils'
import { 
  query,
  info,
  create, 
  remove, 
  update, 
  selection,
  allList,
  priceGroup,
  rechargeList,
  recharge,
  interfaceCallList
} from 'services/organization'
import { priceGroupList } from 'services/price'

import { pageModel } from 'utils/model'

const { prefix } = config

export default modelExtend(pageModel, {
  namespace: 'organization',

  state: {
    currentItem: {},
    modalVisible: false,
    modalType: 'create',
    selectedRowKeys: [],
    isMotion: window.localStorage.getItem(`${prefix}userIsMotion`) === 'true',
    editingKey: '',
    organizationList:[],
    parentOrganization: '',
    allList: [],
    visibleOperator: false,
    visibleApi: false,
    visibleBusiness: false,
    visibleGroup: false,
    visibleBalance: false,
    visibleRecharge: false,
    visible:false,
    currentOrganization: {},
    priceGroupList: [],
    rechargeList: [],
    apiList: []
  },

  subscriptions: {
    setup ({ dispatch, history }) {
      history.listen((location) => {
        if (location.pathname === '/app/organization') {
          dispatch({
            type: 'queryAllList',
            payload: location.query,
          })
        }
      })
    },
  },

  effects: {

    * query ({ payload = {} }, { call, put }) {
      const data = yield call(query, payload);
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * queryWord ({ payload = {} }, { call, put }) {
      console.log('1111')
    },
    * changePage({ payload }, { call, put }) {
      const data = yield call(query, { page: payload.page, pageSize: payload.pageSize })
      if (data) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.page.list,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          },
        })
      }
    },
    * delete ({ payload }, { call, put, select }) {
      const data = yield call(remove, { id: payload })
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * multiDelete ({ payload }, { call, put }) {
      const data = yield call(remove, payload)
      if (data.success) {
        yield put({ type: 'updateState', payload: { selectedRowKeys: [] } })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * create ({ payload }, { call, put }) {
      const data = yield call(create, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * update ({ payload }, { select, call, put }) {
      const id = yield select(({ organization }) => organization.currentItem.id)
      const newUser = { ...payload, id }
      const data = yield call(update, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
        yield put({ type: 'query' })
      } else {
        throw data
      }
    },

    * selection ({payload},{ call, put }) {
      const {modalType} = payload
      const data = yield call(selection)
      if (data.success) {
        let parentOrganization = ''
        if(payload.currentItem){
          const id = payload.currentItem.parentId
          let dataParent = ''
          if(id===0){
            parentOrganization='默认机构'
          }else{
            dataParent = yield call(info,{id})
            parentOrganization=dataParent.organization.name
          }
        }else{
          parentOrganization = ''
        }
        yield put({
          type: 'parentOrganization',
          payload: {
            parentOrganization
          }
        })

        yield put({
          type: 'showModal',
          payload: {
            modalType,
            organizationList:data.organizationList,
            currentItem:payload.currentItem?payload.currentItem:''
          }
        })
      } else {
        throw data
      }
    },

    * queryAllList ({ payload = {} }, { call, put }) {
      const data = yield call(allList, payload);
      if (data) {
        yield put({
          type: 'queryAllListSuccess',
          payload: {
            allList: data.organizationList,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.organizationList.length,
            },
          },
        })
      }
    },

    //显示接口调用
    * showApi ({ payload = {} }, { call, put }) {
      const data = yield call(interfaceCallList, {organizationId: payload.currentOrganization.id})
      if (data) {
        yield put({
          type: 'updateState',
          payload: {
            apiList: data.recordList,
            currentOrganization: payload.currentOrganization,
            visible: true,
            visibleApi: true,
          }
        })
      }
    },

    //显示价格组
    * showGroup ({ payload = {} }, { call, put }) {
      const data = yield call(priceGroupList, payload)
      if (data) {
        yield put({
          type: 'updateState',
          payload: {
            priceGroupList: data.priceGroupList,
            currentOrganization: payload.currentOrganization,
            visible: true,
            visibleGroup: true
          }
        })
      }
    },

    //设置价格组
    * settingPriceGroup ({ payload = {} }, { call, put }) {
      const data = yield call(priceGroup, payload)
      if (data) {
        yield put({type: 'queryAllList'})
        yield put({type: 'hideModal'})
      }
    },


    //显示余额
    * showBalance ({ payload = {} }, { call, put }) {
      yield put({
        type: 'updateState',
        payload: {
          currentOrganization: payload.currentOrganization,
          visible: true,
          visibleBalance: true
        }
      })
    },
    
    //设置余额
    * setBlance ({ payload = {} }, { call, put }) {
      const data = yield call(recharge, payload)
      if (data) {
        yield put({type: 'queryAllList'})
        yield put({type: 'hideModal'})
      }
    },

    //显示充值记录
    * showRecharge ({ payload = {} }, { call, put }) {
      const data = yield call(rechargeList, {organizationId: payload.currentOrganization.id})
      if (data) {
        yield put({
          type: 'updateState',
          payload: {
            rechargeList: data.page.list,
            currentOrganization: payload.currentOrganization,
            visible: true,
            visibleRecharge: true,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.page.totalCount,
            },
          }
        })
      }
    },

  },

  reducers: {

    showModal (state, { payload }) {
      return { ...state, ...payload, visible:true,modalVisible: true }
    },

    hideModal (state) {
      return { 
        ...state, 
        visible:false,
        modalVisible: false ,
        visibleOperator: false,
        visibleApi: false,
        visibleBusiness: false,
        visibleGroup: false,
        visibleBalance: false,
        visibleRecharge: false,
      }
    },

    switchIsMotion (state) {
      window.localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion)
      return { ...state, isMotion: !state.isMotion }
    },

    editingKey(state,{payload}) {
      return {...state,...payload}
    },

    parentOrganization(state,{payload}) {
      return {...state,...payload}
    },

    queryAllListSuccess (state,{payload}) {
      return {...state,...payload}
    },

    showOperator (state,{payload}) {
      console.log(payload);
      return {...state,...payload, visibleOperator: true, visible:true}
    },

    showBusiness (state,{payload}) {
      return {...state,...payload,visibleBusiness: true, visible:true}
    },
  },
})
